package com.doujiang.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 评论管理对象 comment
 * 
 * @author 王伟舰
 * @date 2025-07-19
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Comment implements Serializable
{
    private static final long serialVersionUID = 1L;

    /** 评论ID */
    @TableId(type = IdType.AUTO)
    private Long id;

    /** 用户ID */

    private Long userId;

    /** 电影ID */

    private Long movieId;

    /** 评论内容 */

    private String content;

    /** 评论时间 */
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date createdAt;

    /** 点赞数量 */
    private Integer useful;

    /** $column.columnComment */
    @TableLogic
    private Long deleted;

    // 👇 新增字段：用于数据库存储的 JSON 字符串
    private String likesJson;

    // 👇 运行时使用的 List<Long>，不映射数据库字段
    @TableField(exist = false)
    private List<Long> likes = new ArrayList<>();
    
    // 👇 用户信息字段，不映射数据库字段
    @TableField(exist = false)
    private String username;
    
    @TableField(exist = false)
    private String userAvatar;
    
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 从 likesJson 加载 likes 列表（如从数据库读取时）
    public void parseLikesJson() {
        if (likesJson == null || likesJson.isEmpty()) {
            likes = new ArrayList<>();
        } else {
            try {
                likes = new ArrayList<>(Arrays.asList(objectMapper.readValue(likesJson, Long[].class)));
            } catch (Exception e) {
                likes = new ArrayList<>();
            }
        }
    }


        // 将 likes 列表写入 likesJson（如保存到数据库前）
    public void serializeLikesJson() {
        try {
            likesJson = objectMapper.writeValueAsString(likes);
        } catch (Exception e) {
            likesJson = "[]";
            e.printStackTrace();  // 👈 添加日志
        }
    }

}
